package ln.javatest.day01.demo01;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/*
登录的练习：
    1.通过键盘录入用户名和密码
    2.判断用户是否登录成功
 */
public class JDBCDemo06 {
    public static void main(String[] args) {
        //1.键盘录入，接受用户名和密码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String username = sc.next();
        System.out.println("请输入密码");
        String password = sc.next();
        //2.调用方法
        boolean flag = new JDBCDemo06().login(username, password);
        //3.判断结果，输出不同语句
        if(flag){
            //登录成功
            System.out.println("登陆成功");
        }else{
            System.out.println("用户或密码错误");
        }
    }
    //登录方法
    public boolean login(String username,String password){
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        if(username==null || password==null){
            return false;
        }
        //连接数据库判断是否登录成功

        //1.获取连接
        try {
            conn = JDBCUtils.getConnection();
            //2.定义sql
            String sql = "select * from user where username = '"+username+"' and password = '"+password+"'";
            //3.获取执行sql的对象
            stat = conn.createStatement();
            //4.执行查询
            rs = stat.executeQuery(sql);
            //5.判断
            return rs.next();  //有下一行返回ture
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.close(rs,stat,conn);
        }
        return false;
    }
}
